import 'dart:async';
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_rider/main/page/image_viewer_page.dart';
import 'package:flutter_rider/main/widgets/base/detail_flexStart_layout.dart';
import 'package:flutter_rider/main/widgets/base/detail_flexStart_undeline_layout.dart';
import 'package:flutter_rider/main/widgets/base/kv_layout.dart';
import 'package:flutter_rider/main/widgets/base/order_track_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_layout.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';
import 'package:flutter_rider/module/mine/mine_router.dart';
import 'package:flutter_rider/module/mine/provider/mine_provider.dart';
import 'package:flutter_rider/module/task/page/task_detail_map.dart';
import 'package:flutter_rider/module/task/task_router.dart';
import 'package:flutter_rider/routers/fluro_navigator.dart';
import 'package:flutter_rider/utils/open_utils.dart';
import 'package:flutter_rider/module/task/page/delivery_info_page.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/event/click_far_call_event.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/refresh_order_event.dart';
import 'package:flutter_rider/main/page/address_page.dart';
import 'package:flutter_rider/main/page/far_call_page.dart';
import 'package:flutter_rider/event/task_to_map_event.dart';
import 'package:flutter_rider/utils/extension.dart';

import '../../../event/loc_top_event.dart';
import '../../../event/refresh_map_event.dart';
import '../../mine/models/truck_model.dart';

class TaskDetailPage extends StatefulWidget {
  String id;
  TaskDetailPage(this.id, {Key? key}) : super(key: key);

  @override
  State createState() => TaskDetailPageState();
}

class TaskDetailPageState extends State<TaskDetailPage> {
  final StateLayoutController _stateLayoutController = StateLayoutController();
  // final ScrollController _scrollController = ScrollController();
  dynamic _data;
  late StreamSubscription _eventFn1;
  late StreamSubscription _eventFn2;
  bool _showZh = false;
  bool _showXh = false;
  int _times = 0;
  late Timer _timer;
  Timer? _refreshTimer;
  bool refresh = true;
  bool canScroll = false;
  double _height = 0.0;
  int _currentIndex = 1;

  /// 指针位置
  double dy = 0;

  /// 手势 0向上 1向下
  int gesture = 0;
  int z = 0; // 相减得正
  int f = 0; //

  @override
  void initState() {
    super.initState();
    initButton();
    _eventFn1 = eventBus.on<ClickFarCallEvent>().listen((event) {
      _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
        _countDown();
      });
    });
    _eventFn2 = eventBus.on<RefreshOrderEvent>().listen((event) {
      _stateLayoutController.reload();
      eventBus.fire(RefreshMapEvent());
    });
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      _countDown();
    });
    _refreshTimer = Timer.periodic(const Duration(seconds: 2), (timer) {
      _stateLayoutController.reload();

    });
  }

  @override
  void dispose() {
    super.dispose();
    _eventFn1.cancel();
    _eventFn2.cancel();
    _timer.cancel();
    _recordLastSecond();
    _refreshTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // backgroundColor: UIColor.color_main,
      // appBar: UTitleLayout.getBackTitle(context, "任务详情"),
      body: StateLayout(
        url: "/waybill_mission/detail?id=${widget.id}",
        controller: _stateLayoutController,
        childBuilder: _renderContent,
        dataCallback: (data) {
          _data = data;
          eventBus.fire(TaskToMapEvent());
        },
      ).padding(EdgeInsets.only(
          left: MediaQuery.of(context).padding.left,
          right: MediaQuery.of(context).padding.right)),
    );
  }

  Widget _renderContent(dynamic data) {
    return Stack(
      children: [
        // 发货  取货
        // Expanded(
        //   child:
        TaskDetailMapPage(_data["operation"],
            distance: _data["distance"],
            eta: _data["eta"],
            carLat: _data["lat"] == "" ? 0.0 : toDouble(_data["lat"]),
            carLng: _data["lng"] == "" ? 0.0 : toDouble(_data["lng"]),
            stations: [
              {
                "id": "1001",
                "lat": _data["pick_station_lat"] == ""
                    ? 0.0
                    : toDouble(_data["pick_station_lat"]),
                "lng": _data["pick_station_lng"] == ""
                    ? 0.0
                    : toDouble(_data["pick_station_lng"]),
                "stationName": "${_data["pick_station_name"]}"
              },
              {
                "id": "1002",
                "lat": _data["delivery_station_lat"] == ""
                    ? 0.0
                    : toDouble(_data["delivery_station_lat"]),
                "lng": _data["delivery_station_lng"] == ""
                    ? 0.0
                    : toDouble(_data["delivery_station_lng"]),
                "stationName": "${_data["delivery_station_name"]}"
              }
            ]
            // ),
            ),
        Column(
          children: [const Spacer(), _renderContainer(data)],
        )

        // GestureDetector(
        //   onTapDown:(details){
        //     //点击屏幕立即触发此方法
        //     print("点击屏幕立即触发此方法");
        //   },
        //   onVerticalDragStart:(details){
        //     //与屏幕接触，可能会开始垂直移动
        //     print("与屏幕接触，可能会开始垂直移动$details");
        //   },
        //   onVerticalDragUpdate:(details){
        //     print(details.globalPosition.dy);
        //     double screen30percentage = MediaQuery.of(context).size.height * 0.3;
        //     double screen40percentage = MediaQuery.of(context).size.height * 0.4;
        //     double screen50percentage = MediaQuery.of(context).size.height* 0.5;
        //     double screen60percentage = MediaQuery.of(context).size.height * 0.6;
        //     double screen90percentage = MediaQuery.of(context).size.height* 0.9;
        //     // 上层
        //     if(details.globalPosition.dy<screen50percentage) {
        //       eventBus.fire(MapHeightEvent(screen30percentage));
        //     }
        //     // 中间层
        //     if(screen40percentage<details.globalPosition.dy &&  details.globalPosition.dy< screen90percentage) {
        //       eventBus.fire(MapHeightEvent(screen50percentage));
        //     }
        //     // 下层
        //     if(screen60percentage<details.globalPosition.dy) {
        //       eventBus.fire(MapHeightEvent(screen90percentage));
        //     }
        //   },
        //   onVerticalDragDown: (details) {
        //     print(details);
        //
        //   },
        //   child: Expanded(
        //     // child: SingleChildScrollView(
        //     //   controller: _scrollController,
        //     child: Column(
        //       children: [
        //         (data["car_no"] == "" && !_showXh && data["status"] == 1) || (data["car_no"] == "" && !_showZh && data["status"] == 1) ? 0.wspace : _renderTop(),
        //         12.hspace,
        //         _deliverInfo(_data),
        //         10.hspace,
        //         _consigneeInfo(_data),
        //         10.hspace,
        //         _renderTaskInfo(_data),
        //         10.hspace,
        //         _renderProductInfo(),
        //         10.hspace,
        //         // flag ? _renderButtom() : 0.wspace,
        //         SizedBox(height: MediaQuery.of(context).padding.bottom),
        //       ],
        //     ),
        //
        //   ),
        //
        // ),
      ],
    );
  }

  Widget _renderContainer(dynamic data) {
    bool flag =
        ((_data["operation"] == 0 || _data["operation"] == 1) && _showZh) ||
            (_data["operation"] == 2 && _showXh) ||
            _data["car_no"] != "";
    double screen50percentage =
        MediaQuery.of(context).size.height * 0.5 - 60 - (flag ? 80 : 0);
    return GestureDetector(
        onTapDown: (details) {
          //点击屏幕立即触发此方法
          print("每次用户与屏幕接触时触发");
        },
        onTapUp: (details) {
          //点击屏幕立即触发此方法
          print("当用户停止触摸屏幕时");
        },
        onTap: () {
          print("当屏幕被短暂触摸时");
        },
        onVerticalDragEnd: (details) {
          //与屏幕接触，可能会开始垂直移动

          double screen01percentage = MediaQuery.of(context).size.height * 0.01;
          double screen40percentage = MediaQuery.of(context).size.height * 0.4;
          // double screen50percentage = MediaQuery.of(context).size.height* 0.5;
          double screen60percentage = MediaQuery.of(context).size.height * 0.6;
          print(MediaQuery.of(context).size.height * 0.8);
          double screen90percentage =
              MediaQuery.of(context).size.height * 0.9 - 60 - (flag ? 80 : 0);
          double screen100percentage = MediaQuery.of(context).size.height;

          // 上层
          print(dy);
          print(screen50percentage);
          print(_currentIndex);
          print(gesture);

          // Tip.show("${z}--${f}");
          print("===============");
          print(screen100percentage - MediaQuery.of(context).size.height * 0.8);
          if (dy < screen50percentage &&
              (_currentIndex == 1 || _currentIndex == 2) &&
              z > f) {
            setState(() {
              _height = screen90percentage;
              _currentIndex = 0;
              canScroll = true;
            });
            eventBus.fire(LocToptEvent(50,MediaQuery.of(context).size.height));
          } else if (screen50percentage < dy && _currentIndex == 1 && z > f) {
            setState(() {
              _height = screen90percentage;
              _currentIndex = 0;
              canScroll = true;
            });
            eventBus.fire(LocToptEvent(30,MediaQuery.of(context).size.height));
          } else if (dy < screen50percentage &&
              dy >
                  (screen100percentage -
                      screen100percentage -
                      MediaQuery.of(context).size.height * 0.8) &&
              _currentIndex == 0 &&
              z < f) {
            setState(() {
              _height = screen50percentage;
              _currentIndex = 1;
              canScroll = false;
            });
            eventBus.fire(LocToptEvent(200,MediaQuery.of(context).size.height/2));
          } else if (screen50percentage < dy &&
              (_currentIndex == 0 || _currentIndex == 1) &&
              z < f) {
            setState(() {
              _height = screen01percentage;
              _currentIndex = 2;
              canScroll = false;
            });
            eventBus.fire(LocToptEvent(350,MediaQuery.of(context).size.height));
          } else if (screen50percentage < dy &&
              dy < (screen100percentage - screen01percentage) &&
              _currentIndex == 2 &&
              z > f) {
            setState(() {
              _height = screen50percentage;
              _currentIndex = 1;
              canScroll = false;
            });
            eventBus.fire(LocToptEvent(200,MediaQuery.of(context).size.height/2));
          }
          z = 0;
          f = 0;
        },
        onPanStart: (details) {
          print("平移");
        },
        onVerticalDragUpdate: (details) {
          // 手势向上 30 20 10
          // 手势向下 10 20 30
          print("**********${details.globalPosition.dy}");
          gesture = dy - details.globalPosition.dy > 0 ? z++ : f++;
          print("${z}---${f}");
          dy = details.globalPosition.dy;
        },
        child: Column(children: [
          (data["car_no"] == "" && !_showXh && data["status"] == 1) ||
                  (data["car_no"] == "" && !_showZh && data["status"] == 1)
              ? 0.wspace
              : _renderTop(),
          Container(
            height: 12.rpx,
            color: UIColor.color_main,
          ),
          AnimatedContainer(
            width: double.infinity,
            height: _height > 0 ? _height : screen50percentage,
            curve: Curves.easeIn,
            duration: const Duration(milliseconds: 300),
            // child:Container(
            //   width: double.infinity,
            //   height: _height>0?_height:screen50percentage,
            //   color: UIColor.color_content,
            //child:Expanded(
            child: SingleChildScrollView(
                physics: canScroll
                    ? const AlwaysScrollableScrollPhysics()
                    : const NeverScrollableScrollPhysics(),
                child: Column(children: [
                  // (data["car_no"] == "" && !_showXh && data["status"] == 1) || (data["car_no"] == "" && !_showZh && data["status"] == 1) ? 0.wspace : _renderTop(),
                  _deliverInfo(_data),
                  Container(
                    height: 10.rpx,
                    color: UIColor.color_main,
                  ),
                  _consigneeInfo(_data),
                  Container(
                    height: 10.rpx,
                    color: UIColor.color_main,
                  ),
                  _renderTaskInfo(_data),
                  Container(
                    height: 10.rpx,
                    color: UIColor.color_main,
                  ),
                  _renderProductInfo(),
                  Container(
                    height: 10.rpx,
                    color: UIColor.color_main,
                  ),
                  // SizedBox(height: MediaQuery.of(context).padding.bottom),
                ])
                //)
                //)
                ),
          ),
          flag ? _renderButtom() : 0.wspace,
        ]));
  }

  Widget _deliverInfo(dynamic _data) {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          Container(
            padding: EdgeInsets.only(
                left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
            alignment: Alignment.centerLeft,
            child: UText.get("发货信息", UIColor.color_primary, 14.rpx,
                fw: FontWeight.w600, textAlign: TextAlign.left),
          ),
          Container(
            height: 0.5.rpx,
            width: MediaQuery.of(context).size.width - 16.rpx,
            color: UIColor.color_divider,
            margin: EdgeInsets.only(left: 16.rpx),
          ),
          12.hspace,
          DetailFlexStartLayout('发货人', _data["waybill"]["pick_username"],
              pixel: 14.rpx),
          12.hspace,
          DetailFlexStartUndelineLayout('发货电话', _data["waybill"]["pick_tel"],
              pixel: 14.rpx),
          12.hspace,
          DetailFlexStartLayout('发货地址', _data["waybill"]["pick_address"],
              pixel: 14.rpx),
          12.hspace,
          DetailFlexStartLayout('详细描述', _data["waybill"]["pick_addr_desc"],
              pixel: 14.rpx),
          12.hspace,
          DetailFlexStartLayout('发货车牌', _data["waybill"]["pick_car_plate"],
              pixel: 14.rpx),
          12.hspace,
        ],
      ),
    );
  }

  Widget _consigneeInfo(dynamic _data) {
    return Container(
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        children: [
          Container(
              padding: EdgeInsets.only(
                  left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
              alignment: Alignment.centerLeft,
              child: Row(
                children: [
                  UText.get("收货信息", UIColor.color_primary, 14.rpx,
                      fw: FontWeight.w600, textAlign: TextAlign.left),
                  8.wspace,
                  _data["modified"]?SvgPicture.asset(R.image_update,
                      width: 46.rpx, height: 20.rpx):0.wspace,
                  const Spacer(),
                  GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      if (_data["operation"] == 0 ||
                          _data["operation"] == 1 ||
                          _data["operation"] == 2) {
                        OpenUtils.open(
                            context,
                            AddressInfoPage(
                              _data["delivery_station_name"],
                              _data["delivery_station_id"],
                              _data["delivery_station_alias_id"],
                              _data["delivery_station_alias_name"],
                              _data["delivery_username"],
                              _data["delivery_tel"],
                              _data["delivery_address"],
                              _data["delivery_car_plate"],
                              _data["delivery_addr_desc"],
                              _data["waybill"]["mission_num"],
                              _data["no"],
                            ));
                      }
                    },
                    child: UText.get(
                        "去修改",
                        _data["operation"] == 0 ||
                                _data["operation"] == 1 ||
                                _data["operation"] == 2
                            ? UIColor.color_primary
                            : UIColor.color_border,
                        14.rpx,
                        fw: FontWeight.w600),
                  )
                ],
              )),
          Container(
            height: 0.5.rpx,
            width: MediaQuery.of(context).size.width - 16.rpx,
            color: UIColor.color_divider,
            margin: EdgeInsets.only(left: 16.rpx),
          ),
          12.hspace,
          DetailFlexStartLayout('收货人', _data["delivery_username"],
              pixel: 14.rpx),
          12.hspace,
          DetailFlexStartUndelineLayout('收货电话', _data["delivery_tel"],
              pixel: 14.rpx),
          12.hspace,
          SizedBox(
            child: Row(
              children: [
                16.wspace,
                SizedBox(
                    width: 80.rpx,
                    child: UText.get("收货地址", UIColor.color_t7, 14.rpx)),
                Expanded(
                    child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () {
                    if (_data["operation"] == 0 ||
                        _data["operation"] == 1 ||
                        _data["operation"] == 2) {
                      OpenUtils.open(
                          context,
                          AddressPage(
                              2, _data["no"], _data["waybill"]["mission_num"]));
                    }
                  },
                  child: Row(children: [
                    LimitedBox(
                      maxWidth: 240.rpx,
                      child: Text(_data["delivery_address"],
                          style: TextStyle(
                              color: UIColor.color_t1, fontSize: 14.rpx),
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2),
                    ),
                    const Spacer(),
                    _data["operation"] == 0 ||
                            _data["operation"] == 1 ||
                            _data["operation"] == 2
                        ? Icon(Icons.navigate_next,
                            size: 20.rpx, color: UIColor.color_t3)
                        : 0.wspace,
                  ]),
                )),
                16.wspace,
              ],
            ),
          ),
          12.hspace,
          DetailFlexStartLayout('详细描述', _data["delivery_addr_desc"],
              pixel: 14.rpx),
          12.hspace,
          Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
            16.wspace,
            SizedBox(
                width: 80.rpx,
                child: UText.get("收货车牌", UIColor.color_t7, 14.rpx)),
            GestureDetector(
              onTap: () {
                if (_data["delivery_trunk_id"] > 0) {
                  int id = _data['delivery_trunk_id'];
                  Api.getx(context, "/user/truck_detail?id=$id",
                      progress: false,
                      success: (data) {
                        var truck = TruckModel.fromMap(data);
                        NavigatorUtils.push(
                            context, MineRouter.outsideCarDetailPage,
                            arguments: {"truck": truck});
                      },
                      failTip: "",
                      fail: (e) {
                        Tip.show(e.msg);
                      });
                }
              },
              child: SizedBox(
                width: 100.rpx,
                child: Text(
                  _data["delivery_car_plate"],
                  style: TextStyle(
                    fontSize: 14.rpx,
                    color: UIColor.color_primary,
                    decoration: _data["delivery_trunk_id"] > 0
                        ? TextDecoration.underline
                        : TextDecoration.none,
                    decorationColor: UIColor.color_primary,
                  ),
                ),
              ),
            ),
            16.wspace,
          ]),
          12.hspace,
        ],
      ),
    );
  }

  Widget _renderTaskInfo(dynamic _data) {
    return Container(
      width: double.infinity,
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(
                left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
            alignment: Alignment.centerLeft,
            child: UText.get("任务信息", UIColor.color_primary, 14.rpx,
                fw: FontWeight.w600, textAlign: TextAlign.left),
          ),
          5.hspace,
          Container(
            height: 0.5.rpx,
            width: MediaQuery.of(context).size.width - 16.rpx,
            color: UIColor.color_divider,
            margin: EdgeInsets.only(left: 16.rpx),
          ),
          12.hspace,
          Row(
            children: [
              Expanded(
                  child: KvLayout("任务编号", _data["no"],
                      pixel: 14.rpx, wspace: 4.wspace)),
              GestureDetector(
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: _data["no"]));
                    Tip.show("已复制到剪贴板");
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 4.rpx),
                    child: SvgPicture.asset(
                      R.image_text_copy,
                      width: 16.rpx,
                      height: 16.rpx,
                    ),
                  )),
              16.wspace
            ],
          ),
          10.hspace,
          Row(
            children: [
              Expanded(
                  child: KvLayout("运单编号", _data["waybill_no"],
                      pixel: 14.rpx, wspace: 4.wspace)),
              GestureDetector(
                  onTap: () {
                    Clipboard.setData(ClipboardData(text: _data["waybill_no"]));
                    Tip.show("已复制到剪贴板");
                  },
                  child: Container(
                    margin: EdgeInsets.only(bottom: 4.rpx),
                    child: SvgPicture.asset(
                      R.image_text_copy,
                      width: 16.rpx,
                      height: 16.rpx,
                    ),
                  )),
              16.wspace
            ],
          ),
          10.hspace,
          KvLayout("店铺名称", _data["waybill"]["merchant_name"] ?? "",
              pixel: 14.rpx),
          10.hspace,
          KvLayout("下单时间", _data["waybill"]["order_created_time"],
              pixel: 14.rpx),
          10.hspace,
        ],
      ),
    );
  }

  Widget _renderProductInfo() {
    List<dynamic> jSku = [];
    try {
      jSku = jsonDecode(_data["waybill"]["sku_option"]);
      Log.i("jSku", jSku);
    } catch (e, st) {
      Log.i("", e, st);
    }
    return Container(
      width: double.infinity,
      decoration: const BoxDecoration(
        color: UIColor.color_content,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            padding: EdgeInsets.only(
                left: 16.rpx, top: 16.rpx, right: 16.rpx, bottom: 12.rpx),
            alignment: Alignment.centerLeft,
            child: UText.get("货物信息", UIColor.color_primary, 14.rpx,
                fw: FontWeight.w600, textAlign: TextAlign.left),
          ),
          5.hspace,
          Container(
            height: 0.5.rpx,
            width: MediaQuery.of(context).size.width - 16.rpx,
            color: UIColor.color_divider,
            margin: EdgeInsets.only(left: 16.rpx),
          ),
          12.hspace,
          KvLayout("货物类别", _data["waybill"]["spu_product_name"], pixel: 14.rpx),
          ...jSku
              .asMap()
              .values
              .map((e) => KvLayout(e["name"], e["val"], pixel: 14.rpx)
                  .padding(EdgeInsets.only(top: 10.rpx)))
              .toList(),
          _renderAmount(),
          12.hspace,
          KvLayout("件数", _data["qty"] == 0?"":_data["qty"].toString() + "件", pixel: 14.rpx),
          12.hspace,
          KvLayout("备注", _data["waybill"]["memo"], pixel: 14.rpx),
          12.hspace,
          // _renderImages(),
        ],
      ),
    );
  }

  Widget _renderAmount() {
    return Container(
        child: _data["waybill"]["unit"] == 2
            ? Column(
                children: [
                  12.hspace,
                  KvLayout("数量（吨）", _data["weight"] == 0?"":(_data["weight"] / 1000.0).toString(),
                      pixel: 14.rpx)
                ],
              )
            : 0.wspace);
  }

  Widget _renderTop() {
    var st = _data["operation"];
    dynamic name;
    if (st == 0) {
      name = "未分配";
    } else if (st == 1) {
      name = "待装货";
    } else if (st == 2) {
      name = "待卸货";
    } else if (st == -1) {
      name = "已取消";
    } else if (st == 3) {
      name = "已完成";
    }
    return Container(
      height: 48.rpx,
      color: UIColor.color_content,
      child: Row(
        children: [
          16.wspace,
          UText.get(name, UIColor.color_t1, 16.rpx),
          30.wspace,
          GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                OpenUtils.pop2(context, OrderTrackLayout(_data));
              },
              child: _renderTopRight(st)),
          16.wspace,
        ],
      ),
    );
  }

  Widget _renderTopRight(int st) {
    return SizedBox(
        width: 260.rpx,
        child: Row(
          children: [
            _data["waybill_no"] != ""
                ? UText.get(_data["car_no"], UIColor.color_primary, 16.rpx,
                    fw: FontWeight.w600)
                : 0.wspace,
            const Spacer(),
            Icon(Icons.navigate_next, size: 20.rpx, color: UIColor.color_t3),
          ],
        ));
  }

  /// 底部按钮【远程呼叫,装货/卸货】
  Widget _renderButtom() {
    var st = _data["operation"];
    return Container(
        width: double.infinity,
        height: 80.rpx,
        decoration: const BoxDecoration(
          color: UIColor.color_content,
        ),
        child: Padding(
            padding: EdgeInsets.all(12.rpx),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _data["car_no"] != "" ? _renderMessage() : 0.wspace,
                (st == 0 || st == 1) && _showZh ? _renderZh() : 0.wspace,
                st == 2 && _showXh ? _renderXh() : 0.wspace,
              ],
            )));
  }

  Widget _renderMessage() {
    return GestureDetector(
        onTap: () {
          OpenUtils.open(
              context,
              FarCallPage(
                  _data["car_no"].toString(), _data["car_id"].toString(),
                  wmNo: _data["no"].toString()));
        },
        child: Container(
            width: 156.rpx,
            height: 40.rpx,
            decoration: BoxDecoration(
                color: UIColor.color_content,
                border:
                    Border.all(width: 1.rpx, color: const Color(0xffE7E7E7)),
                borderRadius: const BorderRadius.all(Radius.circular(60.0))),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  SvgPicture.asset(R.image_message,
                      width: 24.rpx, height: 24.rpx),
                  4.wspace,
                  UText.get("远程呼叫", UIColor.color_t5, 16.rpx)
                ])));
  }

  Widget _renderZh() {
    return Consumer(
      builder: ((context, ref, child) {
        var isWork = ref.read(isWorkProvider);
        return GestureDetector(
            onTap: isWork
                ? () {
                    Api.getx(context,
                        "/waybill_mission/loading_detail?id=${_data["id"]}",
                        progress: false, success: (data) {
                      NavigatorUtils.push(context, TaskRouter.orderLoadPage,
                          arguments: _data["id"].toString());
                    }, failTip: "运单未确认，暂时无法装货", fail: (_) {});
                  }
                : null,
            child: Container(
                width: 156.rpx,
                height: 40.rpx,
                margin: EdgeInsets.only(left: 16.rpx),
                decoration: BoxDecoration(
                    color:
                        isWork ? UIColor.color_primary : UIColor.color_shadow2,
                    borderRadius:
                        const BorderRadius.all(Radius.circular(60.0))),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SvgPicture.asset(R.image_zh,
                          width: 24.rpx, height: 24.rpx),
                      4.wspace,
                      UText.get("装货", UIColor.color_content, 16.rpx)
                    ])));
      }),
    );
  }

  Widget _renderXh() {
    return Consumer(
      builder: ((context, ref, child) {
        var isWork = ref.read(isWorkProvider);
        return GestureDetector(
            onTap: isWork
                ? () {
                    Api.getx(context,
                        "/waybill_mission/loading_detail?id=${_data["id"]}",
                        progress: false, success: (data) {
                      NavigatorUtils.push(context, TaskRouter.orderUnloadPage,
                          arguments: _data["id"].toString());
                    }, failTip: "运单未确认，暂时无法卸货", fail: (_) {});
                  }
                : null,
            child: Container(
                width: 156.rpx,
                height: 40.rpx,
                margin: EdgeInsets.only(left: 16.rpx),
                decoration: BoxDecoration(
                    color:
                        isWork ? UIColor.color_primary : UIColor.color_shadow2,
                    borderRadius:
                        const BorderRadius.all(Radius.circular(60.0))),
                child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      SvgPicture.asset(R.image_xh,
                          width: 24.rpx, height: 24.rpx),
                      4.wspace,
                      UText.get("卸货", UIColor.color_content, 16.rpx)
                    ])));
      }),
    );
  }

  _countDown() async {
    var _sp = await SharedPreferences.getInstance();
    _times = _sp.getInt("_second") ?? 0;
    if (_times > 0) {
      _times -= 1;
      _sp.setInt("_second", _times);
    } else {
      _timer.cancel();
      _times = 0;
      _sp.setInt("_second", 0);
    }
  }

  _recordLastSecond() async {
    var _sp = await SharedPreferences.getInstance();
    _sp.setInt("_second", _times);
  }

  initButton() async {
    var _sp = await SharedPreferences.getInstance();
    _showZh = _sp.getBool("_showZh") as bool;
    _showXh = _sp.getBool("_showXh") as bool;
  }
}
